package com.zzb.framework.param.service;

import com.alibaba.fastjson.JSON;
import com.zzb.framework.cache.CacheComponent;
import com.zzb.framework.common.BaseService;
import com.zzb.framework.param.dao.SysParamDAO;
import com.zzb.framework.param.entity.SysParam;

import com.zzb.framework.common.BaseResponse;
import com.zzb.framework.common.ServiceException;
import com.zzb.framework.role.entity.IUser;
import com.zzb.framework.utils.StringToTTypeUtil;
import com.zzb.framework.validator.annotation.ValidatorEnabled;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统配置表 service类
 */
@Service("sysParamService")
public class SysParamService extends BaseService<SysParamDAO, SysParam> {
    private static final Logger logger = LoggerFactory.getLogger(SysParamService.class);
    @Autowired
    private CacheComponent cacheComponent;
    @Autowired
    private SysParamDAO sysParamDAO;

    @Override
    public SysParamDAO getDAO() {
        return sysParamDAO;
    }

    /**
     * 删除系统配置表
     */
    @Transactional
    public BaseResponse deleteSysParam(String id, IUser operate) throws ServiceException {
        return deleteById(id);
    }

    /**
     * 保存系统配置表
     */
    @ValidatorEnabled
    public BaseResponse<SysParam> saveSysParam(SysParam sysParam, IUser operator) throws ServiceException {
        //同时加入缓存
        cacheComponent.put("PARAM", sysParam.getParamName(), sysParam, 0L);
        logger.info("正在保存系统配置表[" + JSON.toJSONString(sysParam) + "][" + JSON.toJSONString(operator) + "]");
        return insertOrUpdate(sysParam, operator);
    }

    /**
     * 获取参数值，如果没有找到配置，则返回空
     */
    public <T> T get(String paramName, Class<T> clazz) {
        //同时加入缓存
        SysParam sysParam = cacheComponent.get("PARAM", paramName, SysParam.class);
        if (sysParam == null) {
            sysParam = getDAO().findTopByParamName(paramName);
        }
        return sysParam != null ? StringToTTypeUtil.convert(sysParam.getParamValue(), clazz) : null;
    }

    /**
     * 获取参数值，如果没有找到配置，则返回默认值
     */
    public <T> T get(String paramName, Class<T> clazz, T defaultValue) {
        SysParam sysParam = cacheComponent.get("PARAM", paramName, SysParam.class);
        if (sysParam == null) {
            sysParam = getDAO().findTopByParamName(paramName);
        }
        return sysParam != null ? StringToTTypeUtil.convert(sysParam.getParamValue(), clazz) : defaultValue;
    }


    /**
     * 获取参数值
     */
    public String getString(String paramName, String defaultValue) {
        SysParam sysParam = cacheComponent.get("PARAM", paramName, SysParam.class);
        if (sysParam == null) {
            sysParam = getDAO().findTopByParamName(paramName);
        }
        return sysParam != null ? sysParam.getParamValue() : defaultValue;
    }

}
